<?php
class Home_MirindaController extends BaseController 
{
	var $returnResult = array ();
	var $configCaltex = array ();
	var $configFacebook = array ();
	var $arrWeekStart = array(0=>"2013-09-18 00:00:00", 1=>"2013-09-25 00:00:00", 2=>"2013-10-02 00:00:00", 3=>"2013-10-09 00:00:00",4=>"2013-10-16 00:00:00",5=>"2013-10-23 00:00:00");
	var	$arrWeekEnd = array(0=>"2013-09-24 23:59:59", 1=>"2013-10-01 23:59:59", 2=>"2013-10-08 23:59:59", 3=>"2013-10-15 23:59:59", 4=>"2013-10-22 23:59:59",5=>"2013-10-31 23:59:59");
		
	public function __construct() 
	{
		parent::__construct ();
		
		$this->returnResult ["TYPE"] = "OK";
		$this->returnResult ["MESSAGE"] = "Khong co loi gi ca";
		$this->returnResult ["DATA"] = null;
		
		$oConfigSys = new Base_ConfigureSystem ();
		$this->configFacebook = $oConfigSys->getGroupConfigure ( CONFIG_FACEBOOK_GROUP_ID );
		$this->configCaltex = $oConfigSys->getGroupConfigure ( CONFIG_CALTEX2013_GROUP_ID );
		
		$this->_view->configFacebook = $this->configFacebook;
	}
	
	public function indexAction() 
	{
		$array_fb_conf = array (
				'appId' => $this->configFacebook ["facebook_appid"],
				'secret' => $this->configFacebook ["facebook_appsecret"],
				'cookie' => true,
				'xfbml' => true,
				'oauth' => true 
		);		
		$facebook = new Facebook ( $array_fb_conf );
		$arrFbData = $facebook->getSignedRequest ();	
		//print_r($arrFbData);exit;		
		if (intval( $arrFbData ["page"] ["liked"] ) != 1) 
		{
			$this->_layout_path = "default/unlike_layout";
			$this->renderView('home/mirinda/like_page');
			return;
		}		
		$currentFbID = $facebook->getUser ();	
		$this->_view->currentFbID = $currentFbID;
		$this->_view->login = 0;
		$this->_view->register = 0;		
		$this->_view->email = "";
		$this->_view->fullname = "";
		$this->_view->total_point = 0;
		
		if ($currentFbID) 
		{			
			$_SESSION["fbid_user"] = $currentFbID;
			$m = new Member();			
			$rowMember = $m->getRow("fbid = ?", array($currentFbID));			
			if ($rowMember)
			{
				$this->_view->email = $rowMember['email'];
				$this->_view->fullname = $rowMember['fullname'];
				$this->_view->total_point = $m->totalGamePointOfMember($rowMember);
			}
		}		
		$this->_view->arrFbData = $arrFbData;
		// Da like roi
		$this->renderView ('home/mirinda/index');
	}
	
	public function getScoresAction()
	{
		$total = 0;
// 		$currentFbID = empty($_POST["fbid"]) == false ? $_POST["fbid"] : 0 ;
		$currentFbID = $this->oParams->varPost('fbid',0);
		if ($currentFbID)
		{			
			$m = new Member();			
			$rowMember = $m->getRow("fbid = ?", array($currentFbID));			
			if ($rowMember){
				$total = $m->totalGamePointOfMember($rowMember);
			}
		}				
		echo $total; exit;
	}	
	
	public function insertAction() 
	{
		// {"fbid": result.id, "name": result.name, "first_name":
		// result.first_name, "last_name": result.last_name, "email":
		// result.email, "birthday":
		// result.birthday,"accessToken":response.authResponse.accessToken}
		
// 		$fbid = "100000338308923";
// 		$name = "duc bui";
// 		$first_name = "duc";
// 		$last_name = "bui";
// 		$email = "duc.bui@sofresh.vn";
// 		$birthday = "12/12/2013";
		
// 		$fbid = $_POST ['fbid'];
// 		$name = $_POST ['name'];
// 		$first_name = $_POST ['first_name'];
// 		$last_name = $_POST ['last_name'];
// 		$email = $_POST ['email'];
// 		$birthday = $_POST ['birthday'];
		
		$fbid = $this->oParams->varPost('fbid','');
		$name = $this->oParams->varPost('name','');
		$first_name = $this->oParams->varPost('first_name','');
		$last_name = $this->oParams->varPost('last_name','');
		$email = $this->oParams->varPost('email','');
		$birthday = $this->oParams->varPost('birthday','');
		
// 		$inPath = "http://graph.facebook.com/{$fbid}/picture?type=large";
// 		$outPath = __UPLOAD_PATH . "/base_{$fbid}.jpg";
		
// 		$this->save_image_from_url($inPath, $outPath);
		
		// data khong ton tai
		$arr = array (
				"fbid" => "$fbid",
				"firstname" => "$first_name",
				"lastname" => "$last_name",
				"email" => "$email",
				"birthday" => "$birthday",
				"fullname" => "$name" 
		);
		
		$m = new Member();
		$current_id = 0;
		$rowMember = $m->getRow("fbid = ?", array ($fbid));
		
		if (empty($rowMember )) 
		{
			$current_id = $m->insert($arr);
		}

		// = 0 => cho way luon, du lieu da co
		// = [fb id] => hien form nhap lieu
		// = -1 thang nay co thong tin nhung chia co ic_number => hien form nhap
		// lieu
		
		echo $fbid.",".$name;		
		die();
	}
	
	public function updateGameAction()
	{
		$fbid = $this->oParams->varPost('fbid');
		$game_code = $this->oParams->varPost('game_code');

		// fbid, game_code		
		if (empty($fbid) || $fbid == 'undefined' || empty($game_code))
// 		if (empty($_POST['fbid']) || empty($_POST['game_code']) || $_POST['fbid'] == 'undefined')
		{
			echo "0";
			exit();
		}
			
// 		$fbid = $this->oParams->varPost('fbid','');
// 		$game_code = $this->oParams->varPost('game_code','');
		$game_score = $this->oParams->varPost('score','');
		$game_mp3_data = $this->oParams->varPost('mp3Data','');
		$game_mp3_name = $this->oParams->varPost('mp3Name','');
		
		$filename_mp3 = date("YmdHisu").".mp3";	
				
		$filecontent = base64_decode($game_mp3_data);					
		if (file_exists(__UPLOAD_PATH."/mp3/".$filename_mp3)){
			@unlink(__UPLOAD_PATH."/mp3/".$filename_mp3);
		}
		$fp = fopen(__UPLOAD_PATH."/mp3/".$filename_mp3, 'wb');
		fwrite($fp, $filecontent);
		fclose($fp);
		
		
// 		$fbid = "100006526693536";
// 		$game_code = "game_01";
	
		$m = new Member();
		
		$rowMember = $m->getRow("fbid = ?", array($fbid));
		
		if ($rowMember == FALSE)
		{
			// data khong ton tai
			// echo "data khong ton tai<br>";
			echo "0";
			die();
		}
		$idRow = intval($this->oParams->varPost("sessionid"));
		$data = array(
					"memberid" => $rowMember['id'],
					"game_code" => $game_code,
					"game_point" => $game_score,
					'timestamp' => date("Y-m-d H:i:s"),
					"game_mp3_data" => $filename_mp3,
					"game_mp3_name" => $game_mp3_name);		
					
		if($idRow == 0)
		{
			// Insert 1 dong du lieu vao Member Detail
			$last_insert_id = $m->insertMemberDetai($data);	
			echo $last_insert_id > 0 ? $last_insert_id : "0";
			exit();
		}else
		{
			$updateid = $m->updateMemberDetail($idRow , $data);
			echo $updateid > 0 ? "1" : "0";
			exit();
		}		
	}
	
	public function getCurrentWeekAction()
	{
		$dateNow = time();
		$totalWeek = 0;
		for($i = 0; $i < count($this->arrWeekStart); $i++){
			if(strtotime($this->arrWeekStart[$i]) <= $dateNow && strtotime($this->arrWeekEnd[$i]) >= $dateNow){
				$totalWeek = $i + 1;
				break;
			}
		}	
		echo $totalWeek; exit;
	}
	
	public function leaderBoardAction($week, $page){		
		//exit;
		$dateNow = time();
		$totalWeek = 0;
		for($i = 0; $i < count($this->arrWeekStart); $i++){
			if(strtotime($this->arrWeekStart[$i]) <= $dateNow && strtotime($this->arrWeekEnd[$i]) >= $dateNow){
				$totalWeek = $i + 1;
				break;
			}
		}		
		
		$perpage = 10;
		$start = $perpage * (intval($page) - 1);
		
		$m = new Member();
		$arrData = $m->getWinnerList($this->arrWeekStart[$week-1],$this->arrWeekEnd[$week-1] ,$start,  $perpage );

		$countWinner = $m->getCountWinnerList($this->arrWeekStart[$week-1],$this->arrWeekEnd[$week-1]);		
		$countWinner = intval($countWinner / $perpage) + ( $countWinner % $perpage == 0 ? 0 : 1 );		
		$this->_view->arrData = $arrData;	
		$this->_view->countWinner = $countWinner;
		$this->_view->totalWeek = $totalWeek;		
		$this->_view->week = $week;	
		
		$this->_view->startWeek = $this->arrWeekStart;		
		$this->_view->endWeek = $this->arrWeekEnd;		
		
		$data_content = $this->_view->fetch('home/mirinda/leader_board');
	
		echo $data_content;
		die();		
	}
	
	/*public function leaderBoardAllAction($week){	
		//exit;
		$page = 1;
		$perpage = 10;
		$start = $perpage * (intval($page) - 1);
		
		$dateNow = time();
		$totalWeek = 0;
		for($i = 0; $i < count($this->arrWeekStart); $i++){
			if(strtotime($this->arrWeekStart[$i]) <= $dateNow && strtotime($this->arrWeekEnd[$i]) >= $dateNow){
				$totalWeek = $i + 1;
				break;
			}
		}	
		
		$m = new Member();	
		$arrData = array();
		if(false){			
			//for($i = 0; $i < count($this->arrWeekStart); $i++){		
				$arr = $m->getWinnerListAll($this->arrWeekStart[0],$this->arrWeekEnd[5]);	
				while (FALSE != ($row = $arr->fetch())) {	
					$row["week"] = $i + 1;
					$arrData[] = $row;
				}
			//}
		}else{
			$arrData = array();
			$arr = $m->getWinnerListTest($this->arrWeekStart[$week-1],$this->arrWeekEnd[$week-1],$start,  $perpage);	
			while (FALSE != ($row = $arr->fetch())) {	
				$row["week"] = $week;
	 			$arrData[] = $row;
			}
		}
				
		$this->_view->arrData = $arrData;	
		$this->_view->countWinner = 1;
		$this->_view->totalWeek = 3;	
			
		$this->_view->startWeek = $this->arrWeekStart;		
		$this->_view->endWeek = $this->arrWeekEnd;		
		
		$data_content = $this->_view->fetch('home/mirinda/leader_board');
	
		echo $data_content;
		die();		
	}*/
	
	public function getShareFacebookAction()
	{
		if($this->oParams->isPost())
		{
			$fbid = $this->oParams->varPost('fbid');
			$scores = $this->oParams->varPost('scores');
			if(!empty($fbid))
			{
				$m = new Member();
				$arrData = $m->getCountNumShare($fbid);
				$numShare = $arrData["numshare"];
				$scoresShare = $arrData["scores"];
				$objShare = 0;
				if($numShare < 3 && $scores > $scoresShare && strtotime($arrData["dateshare"])  <= time()){
					$objShare = 1;
				}
				print_r(json_encode(array("status" => $objShare)));exit;
			}
		}else
		{
			die('Nothing!!!!!!!!!!!!!!!!!!!!!');
		}
	}
	
	public function updateShareFacebookAction()
	{
		if($this->oParams->isPost())
		{			
			$fbid = $this->oParams->varPost('fbid');	
			$scores = $this->oParams->varPost('scores');		
			if(!empty($fbid))
			{
				$m = new Member();
				$arrData = $m->updateShareFacebook($fbid , $scores);				
				print_r(json_encode(array("fbid" => $fbid)));exit;
			}
		}else
		{
			die('Nothing!!!!!!!!!!!!!!!!!!!!!');
		}
	}
	
	public function getTotalPointAction()
	{
		$fbid = $this->oParams->varPost('fbid');
		
		// fbid
		if (empty($fbid))
		{
			echo "0";
			exit();
		}
		
// 		$fbid = "100006526693536";
		$m = new Member();
	
		$rowMember = $m->getRow("fbid = ?", array($fbid));
	
		if ($rowMember == FALSE)
		{
			// data khong ton tai
			// echo "data khong ton tai<br>";
			echo "0";
			die();
		}		
		
		echo $m->totalGamePointOfMember($rowMember);
		die();		
	}
	
	public function termAction()
	{
		$this->_layout_path = "default/none";
		$this->renderView('home/mirinda/term');
	}
	
	private function save_image_from_url($inPath, $outPath)
	{
		$in  = fopen($inPath,  "rb");
		$out = fopen($outPath, "wb");
	
		while (!feof($in)) {
			$read = fread($in, 8192);
			fwrite($out, $read);
		}
	
		fclose($in);
		fclose($out);
	}	

	
}
